<?php
	//use Mts\Request\V20140618 as Mts@;
	class Anchor extends MY_controller{
		function __construct(){
			error_reporting(E_ALL ^ E_NOTICE);
			parent::__construct();
			$this->load->model('users');
			$this->load->model('videos');
			//$this->load->library('redis',array('model'=>'xmpp_redis','channel'=>'im'),'xmpp_redis');
		}

		

		//网宿回调事件（推流成功）
		function callback_start_stream(){
			write_to_db_logs('', date('H:i:s').$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
			$notifyData = $_GET;
			$notifyData['data']=$notifyData;
			if($notifyData && isset($notifyData['data'])){
				$stream_id=$notifyData['data']['id'];
				$node_id=$notifyData['data']['node'];
				$live_list = $this->users->get_live_list(array('stream_id' => $stream_id));
				
				if(!empty($live_list)) {
					foreach($live_list as $key => $val) {
						$is_push = 1;
						$is_live = 1;
						$disconnect_time = 0;
						if(isset($is_push) && isset($disconnect_time)){
							$this->db->update('user', array('is_push'=> $is_push,'is_live'=> $is_live,'start_time'=>time(),'disconnect_time'=>$disconnect_time,'cdn_sign'=>$node_id), "stream_id = '{$stream_id}'");
							//$this->return_status_by_push($val, $is_push);
						}
					}
				}
			}
		}

		//网宿回调事件（推流断开）
		function callback_end_stream(){
			write_to_db_logs('', date('H:i:s').$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
			$notifyData = $_GET;
			$notifyData['data']=$notifyData;
			if($notifyData && isset($notifyData['data'])){
				$stream_id=$notifyData['data']['id'];
				$node_id=$notifyData['data']['node'];
				$live_list = $this->users->get_live_list(array('stream_id' => $stream_id));

				if(!empty($live_list)) {
					foreach($live_list as $key => $val) {
						$is_push = 0;
						$is_live = 0;
						$disconnect_time = time();
						if(isset($is_push) && isset($disconnect_time)){
							$user_info=get_field_by_where('user','cdn_sign,id,start_time',"stream_id = '{$stream_id}'");
							if(!empty($user_info['cdn_sign'])&&$user_info['cdn_sign']!=$node_id){
								write_to_db_logs('ws_end_error_exception', date('H:i:s')." ".$_SERVER['REQUEST_URI']." \r\n");
								die('SUCCESS');
							}
							$data['uid'] =  $user_info['id'];
							$data['start_time'] =  $user_info['start_time'];
							$data['stream_id'] =  $stream_id;
							$data['end_time'] =  time();
							$result = $this->db->insert('user_anchor_log', $data);
							$this->db->update('user', array('is_push'=> $is_push,'is_live'=> $is_live,'start_time'=>0,'disconnect_time'=>$disconnect_time), "stream_id = '{$stream_id}'");
							
							//$this->return_status_by_push($val, $is_push);
						}
					}
				}
			}
		}

		//网宿回调事件（录制回调）
		function callback_create_video(){
			$bodyData = base64_decode(file_get_contents('php://input','r'));
			write_to_db_logs('', date('H:i:s')." ".$_SERVER['REQUEST_URI']." DATA IS:".$bodyData."\r\n");
			$notifyData = json_decode($bodyData, true);
			
			$result=false;
			if(is_array($notifyData['items'])){
				foreach($notifyData['items'] as $ik=>$iv){
					//获取流名stream_id
					$streaminfo=explode('-',$iv['streamname']);
					unset($streaminfo[0]);
					$steam_str=implode('-',$streaminfo);
					$houzhui = substr(strrchr($steam_str, '.'), 1);
					$stream_id = basename($steam_str,".".$houzhui);
					
					$userinfo=$this->users->get_field_by_where('id'," stream_id='".$stream_id."'");
					
					if(empty($userinfo)){
						write_to_db_logs('wscreatvideoerror_' . date('Y-m-d',time()) . '.txt', date('H:i:s')." ".$_SERVER['REQUEST_URI']." getuserinfo fail\r\n");
						die('fail');
					}
					
					if(is_array($iv['detail'])){
						foreach($iv['detail'] as $dk=>$dv){
							$video_duration=$dv['duration'];
							$fsize=$dv['fsize'];
							$url=$dv['url'];
							$startTime=strtotime($dv['startTime']);
							$endTime=strtotime($dv['endTime']);
							$urlarr=explode('--',$url);
							if(!isset($urlarr[1])){
								write_to_db_logs('wscreatvideoerror_' . date('Y-m-d',time()) . '.txt', date('H:i:s')." ".$_SERVER['REQUEST_URI']." begin time error\r\n");
								die('fail');
							}
							
							//去掉视频名字的后缀为了获取时间格式命名的视频时间
							$videonamehouzhui = substr(strrchr($urlarr[1], '.'), 1);
					        $videoname = basename($urlarr[1],".".$videonamehouzhui);
							
							if(stripos($videoname,'_')!==false){//同一个直播的多个录制视频会以_来命名返回
								$timearr=explode('_',$videoname);
								$begin_time=$timearr[0];
							}else{
								$begin_time=$videoname;
							}
							$begin_time=strtotime($begin_time);//转化为时间戳
							
							if($begin_time<=0){
								write_to_db_logs('wscreatvideoerror_' . date('Y-m-d',time()) . '.txt', date('H:i:s')." ".$_SERVER['REQUEST_URI']." begin time error2\r\n");
								die('fail');
							}
							
							$result=$this->add_new_video($userinfo['id'], $url, $fsize, $video_duration, $begin_time, $startTime, $endTime);
							if(!$result){
								write_to_db_logs('wscreatvideoerror_' . date('Y-m-d',time()) . '.txt', date('H:i:s')." ".$_SERVER['REQUEST_URI']." insert video fail\r\n");
							}
						}
					}
				}
			}else{
				write_to_db_logs('wscreatvideoerror_' . date('Y-m-d',time()) . '.txt', date('H:i:s')." ".$_SERVER['REQUEST_URI']." jieshou data exception\r\n");
			}

			if($result){
				die('success');		
			}else{
				die('fail');
			}
		}
		
		function aliyun_callback_record_mp4_live(){
			$notifyData = file_get_contents('php://input','r');
			write_to_db_logs_ali('aliyun_callback_record_mp4_live_1', date('H:i:s')." ".json_encode($notifyData)."\r\n".json_encode($_REQUEST));
			if(empty($notifyData)){
				$notifyData = $_REQUEST;
			}else{
				$notifyData = json_decode($notifyData,TRUE);
				if(empty($notifyData)){
					$xml = simplexml_load_string($notifyData);
					$notifyData = json_decode(json_encode($xml),TRUE);
				}
			}
			write_to_db_logs_ali('aliyun_callback_record_mp4_live', date('H:i:s')." ".'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]."\r\n".json_encode($notifyData)."\r\n".json_encode($_REQUEST));
			$aliyun_mp4_live_log=array();
			if(isset($notifyData['Message'])){
				write_to_db_logs_ali('aliyun_callback_record_mp4_live_message', date('H:i:s')." ".$notifyData['Message']);
				$json_message=json_decode($notifyData['Message']);
				if (strcmp($json_message->{'Type'}, 'Report') == 0) {
					 $activities = $json_message->{'MediaWorkflowExecution'}->{'ActivityList'};
					  $transcode_job_ids = Array();
					  for ($i=0; $i < count($activities); $i++) {
						if (strcmp($activities[$i]->{'Type'}, 'Transcode') == 0) {
						  $transcode_job_ids[] = $activities[$i]->{'JobId'};
						}
					  }
				}else{
					exit;
				}
				
				if (strcmp($json_message->{'Type'}, 'Report') == 0) {
					$activities = $json_message->{'MediaWorkflowExecution'}->{'ActivityList'};
					$snapshot_job_ids = Array();
					for ($i=0; $i < count($activities); $i++) {
						if (strcmp($activities[$i]->{'Type'}, 'Snapshot') == 0) {
						  $snapshot_job_ids[] = $activities[$i]->{'JobId'};
						}
					}
				}
				$notify_data = json_decode($notifyData['Message'] ,true);
				$m3u8_url_arr=explode('/',$notify_data['MediaWorkflowExecution']['Input']['InputFile']['Object']);
				$m3u8_file_name=$m3u8_url_arr[count($m3u8_url_arr)-1];
				$m3u8_file_name_arr=explode('.',$m3u8_file_name);
				$m3u8_file_name=$m3u8_file_name_arr[0];
				//获取m3u8回调
				$mp4_notify = get_field_by_where("aliyun_mp4_live_log", "id", "file_name='{$m3u8_file_name}'");
				if($mp4_notify){
					//$aliyun_mp4_live_log['file_name'] = $m3u8_file_name;
					$aliyun_mp4_live_log['media_work_flow_id'] = $notify_data['MediaWorkflowExecution']['MediaWorkflowId'];
					$aliyun_mp4_live_log['name'] = $notify_data['MediaWorkflowExecution']['Name'];
					$aliyun_mp4_live_log['run_id'] = $notify_data['MediaWorkflowExecution']['RunId'];
					$aliyun_mp4_live_log['mediaId'] = $notify_data['MediaWorkflowExecution']['MediaId'];
					$aliyun_mp4_live_log['bucket'] = $notify_data['MediaWorkflowExecution']['Input']['InputFile']['Bucket'];
					$aliyun_mp4_live_log['location'] = $notify_data['MediaWorkflowExecution']['Input']['InputFile']['Location'];
					$aliyun_mp4_live_log['object'] = $notify_data['MediaWorkflowExecution']['Input']['InputFile']['Object'];
					$aliyun_mp4_live_log['mp4_job'] = join(',', $transcode_job_ids);
					$aliyun_mp4_live_log['pic_job'] = join(',', $snapshot_job_ids);
					$aliyun_mp4_live_log['addtime'] = time(); 
					$this->db->update('aliyun_mp4_live_log',$aliyun_mp4_live_log, "file_name = '{$m3u8_file_name}'");
					@header('HTTP/1.1 204 NoContent');exit;
				}else{
					$aliyun_mp4_live_log['file_name'] = $m3u8_file_name;
					$aliyun_mp4_live_log['media_work_flow_id'] = $notify_data['MediaWorkflowExecution']['MediaWorkflowId'];
					$aliyun_mp4_live_log['name'] = $notify_data['MediaWorkflowExecution']['Name'];
					$aliyun_mp4_live_log['run_id'] = $notify_data['MediaWorkflowExecution']['RunId'];
					$aliyun_mp4_live_log['mediaId'] = $notify_data['MediaWorkflowExecution']['MediaId'];
					$aliyun_mp4_live_log['bucket'] = $notify_data['MediaWorkflowExecution']['Input']['InputFile']['Bucket'];
					$aliyun_mp4_live_log['location'] = $notify_data['MediaWorkflowExecution']['Input']['InputFile']['Location'];
					$aliyun_mp4_live_log['object'] = $notify_data['MediaWorkflowExecution']['Input']['InputFile']['Object'];
					$aliyun_mp4_live_log['mp4_job'] = join(',', $transcode_job_ids);
					$aliyun_mp4_live_log['pic_job'] = join(',', $snapshot_job_ids);
					$aliyun_mp4_live_log['addtime'] = time(); 
					$this->db->insert("aliyun_mp4_live_log", $aliyun_mp4_live_log);
					write_to_db_logs_ali('aliyun_callback_record_mp4_live_insert', date('H:i:s')." ".json_encode($aliyun_mp4_live_log));
				}
			}

			//获取m3u8回调
			$m3u8_notify = get_field_by_where("aliyun_m3u8_live_log", "id", "file_name='{$m3u8_file_name}'");
			if($m3u8_notify){
				$this->aliyun_create_video($m3u8_file_name);
			}
			@header('HTTP/1.1 204 NoContent');
			//exit;
		}
		
		function aliyun_create_video($file_name=''){
			
			include_once 'third_party/aliyun/aliyun-php-sdk-core/Config.php';
			$aliyun_mp4_live_log = get_field_by_where("aliyun_mp4_live_log", "mp4_job,pic_job","file_name='{$file_name}'");
			$this->config->load('aliyun_config');
			$aliyun_config = $this->config->item('aliyun');
			$access_key_id=$aliyun_config['acces_key_id'];
			$access_key_secret=$aliyun_config['acces_key_secret'];
			$profile = DefaultProfile::getProfile('cn-hangzhou',$access_key_id,$access_key_secret);
			$mts_client = new DefaultAcsClient($profile);
			include 'third_party/aliyun/aliyun-php-sdk-mts/Mts/Request/V20140618/QueryJobListRequest.php';
			$QueryJobListRequest->setJobIds($aliyun_mp4_live_log['mp4_job']);
			$QueryJobListRequest->setRegionId('cn-hangzhou');
			$response = $mts_client->getAcsResponse($QueryJobListRequest);
			for ($i=0; $i < count($response->{'JobList'}->{'Job'}); $i++) {
				$output = $response->{'JobList'}->{'Job'}[$i]->{'Output'};
				$output_file = $response->{'JobList'}->{'Job'}[$i]->{'Output'}->{'OutputFile'};
				$video_properties = $response->{'JobList'}->{'Job'}[$i]->{'Output'}->{'Properties'};
				$url='http://'.$output_file->{'Bucket'}.'.'.$output_file->{'Location'}.'.aliyuncs.com/'.urldecode($output_file->{'Object'});
				$video_duration = $video_properties->{'Duration'};
				$fsize=$video_properties->{'FileSize'};
			}
			
			$aliyun_m3u8_live_log = get_field_by_where("aliyun_m3u8_live_log", "stream,start_time,stop_time","file_name='{$file_name}'");
			$stream_id=$aliyun_m3u8_live_log ['stream'];
			$begin_time=$aliyun_m3u8_live_log ['start_time'];
			$startTime=$aliyun_m3u8_live_log ['start_time'];
			$endTime=$aliyun_m3u8_live_log ['stop_time'];
			$userinfo=$this->users->get_field_by_where('id'," stream_id='".$stream_id."'");
			if(empty($userinfo)){
				write_to_db_logs_ali('aliyuncreatvideoerror_' . date('H:i:s') . '.txt', date('H:i:s')." ".$_SERVER['REQUEST_URI']." getuserinfo fail\r\n");
				exit;
			}
			include 'third_party/aliyun/aliyun-php-sdk-mts/Mts/Request/V20140618/QuerySnapshotJobListRequest.php';
			$QuerySnapshotJobListRequest->setSnapshotJobIds($aliyun_mp4_live_log['pic_job']);
			$QuerySnapshotJobListRequest->setRegionId('cn-hangzhou');
			$response = $mts_client->getAcsResponse($QuerySnapshotJobListRequest);
			$pic_url='';
			for ($i=0; $i < count($response->{'SnapshotJobList'}->{'SnapshotJob'}); $i++) {
				$snapshot_config = $response->{'SnapshotJobList'}->{'SnapshotJob'}[$i]->{'SnapshotConfig'};
				$output_file = $response->{'SnapshotJobList'}->{'SnapshotJob'}[$i]->{'SnapshotConfig'}->{'OutputFile'};
				$pic_url='http://'.$output_file->{'Bucket'}.'.'.$output_file->{'Location'}.'.aliyuncs.com/'.urldecode($output_file->{'Object'})."\n";
			}
			
			$result=$this->add_new_video($userinfo['id'], $url, $fsize, $video_duration, $begin_time, $startTime, $endTime,$pic_url);
			if(!$result){
				write_to_db_logs_ali('aliyuncreatvideoerror_' . date('H:i:s') . '.txt', date('H:i:s')." ".$_SERVER['REQUEST_URI']." insert video fail\r\n");
			}
			exit;
		}
		function aliyun_callback_record_m3u8_live(){
			$notifyData = file_get_contents('php://input','r');
			write_to_db_logs_ali('aliyun_callback_record_m3u8_live_1', date('H:i:s')." ".json_encode($notifyData)."\r\n".json_encode($_REQUEST));
			if(empty($notifyData)){
				$notifyData = $_REQUEST;
			}else{
				$notifyData = json_decode($notifyData,TRUE);
				if(empty($notifyData)){
					$xml = simplexml_load_string($notifyData);
					$notifyData = json_decode(json_encode($xml),TRUE);
				}
			}
			write_to_db_logs_ali('aliyun_callback_record_m3u8_live', date('H:i:s')." ".'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]."\r\n".json_encode($notifyData)."\r\n".json_encode($_REQUEST));
			if($notifyData){
				$m3u8_url_arr=explode('/',$notifyData['uri']);
				$m3u8_file_name=$m3u8_url_arr[count($m3u8_url_arr)-1];
				$m3u8_file_name_arr=explode('.',$m3u8_file_name);
				$m3u8_file_name=$m3u8_file_name_arr[0];
				$m3u8_notify = get_field_by_where("aliyun_m3u8_live_log", "id", "file_name='{$m3u8_file_name}'");
				if($m3u8_notify){
					@header('HTTP/1.1 200 OK');
				}else{
					$aliyun_m3u8_live_log=array();
					$aliyun_m3u8_live_log['file_name'] = $m3u8_file_name;
					$aliyun_m3u8_live_log['domain'] = $notifyData['domain'];
					$aliyun_m3u8_live_log['app'] = $notifyData['app'];
					$aliyun_m3u8_live_log['uri'] = $notifyData['uri'];
					$aliyun_m3u8_live_log['stream'] = $notifyData['stream'];
					$aliyun_m3u8_live_log['start_time'] = $notifyData['start_time'];
					$aliyun_m3u8_live_log['stop_time'] = $notifyData['stop_time'];
					$aliyun_m3u8_live_log['addtime'] = time();
					$this->db->insert("aliyun_m3u8_live_log", $aliyun_m3u8_live_log);
					//获取m3u8回调
					$mp4_notify = get_field_by_where("aliyun_mp4_live_log", "id", "file_name='{$m3u8_file_name}'");
					if($mp4_notify){
						$this->aliyun_create_video($m3u8_file_name);
					}
					@header('HTTP/1.1 200 OK');
				}
			}
		}
		
		//啊里云回调事件（推流）
		function aliyun_callback_live(){
			$notifyData = file_get_contents('php://input','r');
			if(empty($notifyData)){
				$notifyData = $_REQUEST;
			}else{
				$notifyData = json_decode($notifyData);
				if(empty($notifyData)){
					$xml = simplexml_load_string($notifyData);
					$notifyData = json_decode(json_encode($xml),TRUE);
				}
			}
			write_to_db_logs_ali('aliyun_callback_live', date('H:i:s')." ".'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]."\r\n".json_encode($notifyData)."\r\n".json_encode($_REQUEST));
			$stream_id=isset($notifyData['id'])?$notifyData['id']:0;
			$this->config->load('aliyun_config');
			$aliyun_config = $this->config->item('aliyun');
			if(isset($notifyData['auth_key'])){
				$notify_auth_key_array=explode('-',$notifyData['auth_key']);
				$Timestamp=$notify_auth_key_array[0];
				$Rand=0;
				$Uid=0;
				$Key=$aliyun_config['auth_key'];
				$md5hash=md5('/'.$aliyun_config['app_name'].'/'.$stream_id.'-'.$Timestamp.'-'.$Rand.'-'.$Uid.'-'.$Key);
				$auth_key=$Timestamp.'-'.$Rand.'-'.$Uid.'-'.$md5hash;
			}
			if(((isset($notifyData['auth_key']) && $notifyData['auth_key']==$auth_key) || !isset($notifyData['auth_key']))&& $stream_id){
				$this->load->library('redis',array('model'=>'anchor_redis','channel'=>'live'),'anchor_redis');
				$live_list = $this->users->get_live_list(array('stream_id' => $stream_id));
				if(isset($notifyData['action']) && $notifyData['action']=='publish'){
					if(!empty($live_list)) {
						foreach($live_list as $key => $val) {
							$last_callback_time=$this->anchor_redis->redis_class->get_anchor_last_callback_time($val['anchor_id']);
							if(intval($last_callback_time) > $notifyData['time']){
								continue;
							}
							if(!empty($notifyData['time'])){
								$this->anchor_redis->redis_class->set_anchor_last_callback_time($val['anchor_id'],$notifyData['time']);
							}
							$is_push = 1;
							$disconnect_time = 0;
							if(isset($is_push) && isset($disconnect_time)){
								$this->db->update('user', array('is_push'=> $is_push,'disconnect_time'=>$disconnect_time), "stream_id = '{$stream_id}'");
								$this->return_status_by_push($val, $is_push);
							}
						}
					}
				}elseif(isset($notifyData['action']) && $notifyData['action']=='publish_done'){
					if(!empty($live_list)) {
						foreach($live_list as $key => $val) {
							$last_callback_time=$this->anchor_redis->redis_class->get_anchor_last_callback_time($val['anchor_id']);
							if(intval($last_callback_time) > $notifyData['time']){
								continue;
							}
							if(!empty($notifyData['time'])){
								$this->anchor_redis->redis_class->set_anchor_last_callback_time($val['anchor_id'],$notifyData['time']);
							}
							$is_push = 0;
							$disconnect_time = time();
							if(isset($is_push) && isset($disconnect_time)){
								$this->db->update('user', array('is_push'=> $is_push,'disconnect_time'=>$disconnect_time), "stream_id = '{$stream_id}'");
								$this->return_status_by_push($val, $is_push);
							}
						}
					}
				}
				echo $this->db->last_query();
			}else{
				write_to_db_logs_ali('aliyun_callback_live', date('H:i:s')." auth_key 验证不通过");
			}
		}

		
		

		//网宿回调事件 临时用 找回丢失的回调（录制回调）
		function linshi_ws_record_finish(){
			echo 888;
			$listarr=array();
			$listarr[]='';
			$listarr[]='';
			$listarr[]='';
			$listarr[]='';
			
			foreach($listarr as $v){
				$bodyData = base64_decode($v);
				write_to_db_logs('', date('H:i:s')." ".$_SERVER['REQUEST_URI']." DATA IS:".$bodyData."\r\n");
				$notifyData = json_decode($bodyData, true);
				
				$result=false;
				if(is_array($notifyData['items'])){
					foreach($notifyData['items'] as $ik=>$iv){
						//获取流名stream_id
						$streaminfo=explode('-',$iv['streamname']);
						unset($streaminfo[0]);
						$steam_str=implode('-',$streaminfo);
						$houzhui = substr(strrchr($steam_str, '.'), 1);
						$stream_id = basename($steam_str,".".$houzhui);
						
						$userinfo=$this->users->get_field_by_where('id'," stream_id='".$stream_id."'");
						
						if(empty($userinfo)){
							write_to_db_logs('wscreatvideoerror_' . date('Y-m-d',time()) . '.txt', date('H:i:s')." ".$_SERVER['REQUEST_URI']." getuserinfo fail\r\n");
							break;
						}
						
						if(is_array($iv['detail'])){
							foreach($iv['detail'] as $dk=>$dv){
								$video_duration=$dv['duration'];
								$fsize=$dv['fsize'];
								$url=$dv['url'];
								$startTime=strtotime($dv['startTime']);
								$endTime=strtotime($dv['endTime']);
								$urlarr=explode('--',$url);
								if(!isset($urlarr[1])){
									write_to_db_logs('wscreatvideoerror_' . date('Y-m-d',time()) . '.txt', date('H:i:s')." ".$_SERVER['REQUEST_URI']." begin time error\r\n");
									break;
								}
								
								//去掉视频名字的后缀为了获取时间格式命名的视频时间
								$videonamehouzhui = substr(strrchr($urlarr[1], '.'), 1);
						        $videoname = basename($urlarr[1],".".$videonamehouzhui);
								
								if(stripos($videoname,'_')!==false){//同一个直播的多个录制视频会以_来命名返回
									$timearr=explode('_',$videoname);
									$begin_time=$timearr[0];
								}else{
									$begin_time=$videoname;
								}
								$begin_time=strtotime($begin_time);//转化为时间戳
								
								if($begin_time<=0){
									write_to_db_logs('wscreatvideoerror_' . date('Y-m-d',time()) . '.txt', date('H:i:s')." ".$_SERVER['REQUEST_URI']." begin time error2\r\n");
									break;
								}
								
								$result=$this->add_new_video($userinfo['id'], $url, $fsize, $video_duration, $begin_time, $startTime, $endTime);
								if(!$result){
									write_to_db_logs('wscreatvideoerror_' . date('Y-m-d',time()) . '.txt', date('H:i:s')." ".$_SERVER['REQUEST_URI']." insert video fail\r\n");
								}
							}
						}
					}
				}else{
					write_to_db_logs('wscreatvideoerror_' . date('Y-m-d',time()) . '.txt', date('H:i:s')." ".$_SERVER['REQUEST_URI']." jieshou data exception\r\n");
				}

				if($result){
					echo 'ok<br>';	
				}else{
					echo 'fail<br>';	
				}
			}
				
			die('allsuccess');
		}

        function add_new_video($uid, $video_url, $video_size, $video_duration, $begin_time, $start_time, $end_time,$pic_url=''){
        	$video_info = get_field_by_where("video", "id", "video_url='" . $video_url."'");
			
			if(!empty($video_info)){
				return false;
			}
        	$anchor_house = get_field_by_where("user", "*", "id=" . $uid);
        	$anchor_log = get_field_by_where("user_anchor_log", "*", " start_time<=".$begin_time." and end_time>=".$begin_time." and uid=" . $uid);
					
			if(!empty($anchor_log)){
				$anchor_view=$anchor_log['view'];
			}else{
				$anchor_view=$anchor_house['h_count'];
			}
			
			if($video_duration<60) return true;//少于1分钟的不存入数据库
			
			$video_data=array();
			$video_data['uid'] 			= $uid;
			$video_data['title'] 		= !empty($anchor_house['title']) ? $anchor_house['title'] : '';
			//$video_data['orinetation'] 	= !empty($anchor_house['orientation']) ? $anchor_house['orientation'] : 0;
			$video_data['status'] 		= 1;
			$video_data['image_url'] 	= $anchor_house['image_url']?$anchor_house['image_url']:$pic_url;
			$video_data['add_time'] 	= time();
			$video_data['start_time'] 	= $start_time;
			$video_data['end_time'] 	= $end_time;
			//$video_data['video_password'] = $anchor_house['house_password'];
			$video_data['cate_id']		= $anchor_house['cate_id'];
			
			$video_data['video_url']=$video_url;
			//$video_data['watermark']		= $anchor_house['watermark'];
			$video_data['duration'] = date("H:i:s", mktime(0, 0, $video_duration));
			$video_data['video_size'] = $video_size;
			if (empty($video_data['video_size'])) {
				return false;
			}
			$user_info = $anchor_house;
			$video_data['click_num']	= $anchor_view;
			
			$this->db->insert('video', $video_data);
			$vid = $this->db->insert_id();
			
			$user_anchor_log_data=array();
			//添加动态数据
			if($vid > 0){
				// $relation_data = array();
				// $relation_data['uid']		= $uid;
				// $relation_data['top_id']	= $vid;
				// $relation_data['type']		= 3;
				// $relation_data['src_type']	= 1;
				// $relation_data['status']	= 1;
				// $relation_data['up_count']	= 0;
				// $relation_data['add_time']	= $video_data['add_time'];
				
				// $this->db->insert("relation", $relation_data);
				
				$reult=$this->users->increase_v_count($uid);
				
				//增加分类视频数量
				// if($video_data['cate_id']>0){
				// 	$this->load->model("m_cate");
				// 	$this->m_cate->increase_count($video_data['cate_id']);
				// }
				
				$user_anchor_log_data['is_video'] 		= 0;
				$user_anchor_log_data['add_video_time'] = time();
				$user_anchor_log_data['v_id'] 			= $vid;
			}
			$msg = 'Create Video Info :'.$this->db->last_query().'insert reslut'.$reult.'<br/>';

			$create_video_log['status'] = 8;
			$create_video_log['msg'] = $msg;
			// $this->db->insert("create_video_log", $create_video_log);

			// if(!empty($user_anchor_log_data)) {
			// 	$this->db->where('id',$val['id']);
			// 	$this->db->update('user_anchor_log', $user_anchor_log_data);
			// }
			$this->db->insert("create_video_log", $create_video_log ? $create_video_log : 'video log is null');
			return true;
        }

		//计划任务设计，直播异常退出，超过3分钟强制退出
		function leave_by_live_list() {
			$live_list = $this->users->get_live_list(array('is_live'=>1),0,10000);
			if(!empty($live_list)) {
				foreach($live_list as $key=>$val) {
					$is_push = $val['is_push'];
					$data = array();
					
					
					if (empty($val['start_time'])) {
						$val['start_time'] = $data['start_time'] = time();
					}
					
					/* 获取房间在线人数 */
					$data['h_count'] = count($this->xmpp_redis->redis_class->get_room_current_members($val['uid']));
					/* 在线人数end */
					$this->db->where('id',$val['uid']);
					$this->db->update('user', $data);
					echo 'Update Anchor Info : '.$this->db->last_query().'<br/>';
					
				}
			}
			echo 'End Plan';
		}
		
		//计划任务设计，结束直播生成视频
		function leave_create_video() {
			//生成视频
			$this->load->library('redis',array('model'=>'anchor_redis','channel'=>'live'),'anchor_redis');
			$anchor_log = $this->users->get_anchor_log(array('cdn'=>1));
			$create_video_log = array();
			$create_video_log['add_time'] = time();
			if(!empty($anchor_log)) {
				foreach($anchor_log as $key=>$val) {
					$is_video = $val['is_video'];
					$create_video_log['anchor_id'] = $val['uid'];
					if($val['cdn'] == 1) {
						
						$stream = $this->anchor_redis->redis_class->qiniu_stream($val['stream_id']);
						$user_anchor_log_data = array();
						$video_data = array();
						
						try {
							// 获取MP4 播放地址
							$name      = $val['start_time'] . '--'. $val['end_time'].'.mp4'; // required
							$format    = 'mp4';           // required
							$start     = (int)$val['start_time'];      // required, in second, unix timestamp
							$end       = (int)$val['end_time'];      // required, in second, unix timestamp
							$pipeline  = "anchor";
							$result = $stream->saveAs($name, $format, $start, $end, $notifyUrl = NULL,$pipeline); # => Array
							$video_data['video_url'] = $result['targetUrl'];
							if (empty($video_data['video_url'])) {
								$msg = 'Create Video Info : Error, video_url Is NULL <br/>';
								echo $msg;
								$create_video_log['status'] = 1;
								$create_video_log['msg'] = $msg . json_encode($result);
								$this->db->insert("create_video_log", $create_video_log);
								continue;
							}
						}catch (Exception $e) {
							$msg = 'Create Video Info : Error, '. $e->getmessage().'<br/>';
							echo $msg;
							$create_video_log['status'] = 2;
							$create_video_log['msg'] = $msg;
							// $this->db->insert("create_video_log", $create_video_log);
						}
						if(empty($start)) {
							$is_video = false;
							$create_video_log['status'] = 3;
							$create_video_log['msg'] = '开始时间为空' . json_encode($val);
							// $this->db->insert("create_video_log", $create_video_log);
						}/*else if ( (time() - $val['add_time']) >= 180 ) { //超过3分钟就不生成视频了（异常情况）
							$is_video = false;
							$user_anchor_log_data['is_video'] = 0;
							$msg = ' NOT Create Video Info : Error, '. date('Y-m-d H:i:s',$val['add_time']) .' <br/>';
							echo $msg;
							$create_video_log['status'] = 4;
							$create_video_log['msg'] = $msg . json_encode($val);
							// $this->db->insert("create_video_log", $create_video_log);
						}*/else {
							$is_video = true;
							$create_video_log['status'] = 5;
							$create_video_log['msg'] = 'is_video = true' . json_encode($val);
							// $this->db->insert("create_video_log", $create_video_log);
						}
					}else if($val['cdn'] == 2) {
						$is_video = false;
						$create_video_log['status'] = 6;
						$create_video_log['msg'] = 'CDN=2' . json_encode($val);
						// $this->db->insert("create_video_log", $create_video_log);
					}else if($val['cdn'] == 4) {
						continue;//网宿不用计划任务去请求生成点播，他们是自动生成点播然后调回调接口通知点播已生成
					}
			
					if($is_video) {
						$anchor_house = get_field_by_where("user", "*", "id=" . $val['uid']);
					
						$video_data['uid'] 			= $val['uid'];
						$video_data['title'] 		= !empty($anchor_house['title']) ? $anchor_house['title'] : '';
						$video_data['orinetation'] 	= !empty($anchor_house['orientation']) ? $anchor_house['orientation'] : 0;
						$video_data['status'] 		= 1;
						$video_data['image_url'] 	= $val['image_url'];
						$video_data['add_time'] 	= time();
						$video_data['cate_id']=$anchor_house['cate_id'];
						
						$qiniu_file_info = json_decode(@file_get_contents($video_data['video_url']."?avinfo"), true);
						$video_data['duration'] = date("H:i:s", mktime(0, 0, $qiniu_file_info['format']['duration']));
						$video_data['video_size'] = $qiniu_file_info['format']['size'];
						if (empty($video_data['video_size'])) {
							$video_url = !empty($video_data['video_url']) ? $video_data['video_url'] : '';
							$msg = 'Create Video Info : Error, video_size Is NULL ' . $video_url . "?avinfo" .' <br/>';
							echo $msg;
							$create_video_log['status'] = 7;
							$create_video_log['msg'] = $msg . json_encode($qiniu_file_info);
							$this->db->insert("create_video_log", $create_video_log);
							
							//修改成失败了就不重试了
							$user_anchor_log_data['is_video'] 		= 0;
							$user_anchor_log_data['add_video_time'] = time();
							$user_anchor_log_data['v_id'] 			= 0;
							
							$this->db->where('id',$val['id']);
							$this->db->update('user_anchor_log', $user_anchor_log_data);
							
							continue;
						}
						$video_data['click_num'] = $val['view'];
						
						$this->db->insert('video', $video_data);
						$vid = $this->db->insert_id();
						
						//添加动态数据
						if($vid > 0){
							$relation_data = array();
							$relation_data['uid']		= $val['uid'];
							$relation_data['top_id']	= $vid;
							$relation_data['type']		= 3;
							$relation_data['src_type']	= 1;
							$relation_data['status']	= $video_data['status'];
							$relation_data['up_count']	= 0;
							$relation_data['add_time']	= $video_data['add_time'];
							
							$this->db->insert("relation", $relation_data);
							
							$this->users->increase_v_count($video_data['uid']);
							
							$user_anchor_log_data['is_video'] 		= 0;
							$user_anchor_log_data['add_video_time'] = time();
							$user_anchor_log_data['v_id'] 			= $vid;
						}
						$msg = 'Create Video Info :'.$this->db->last_query().'<br/>';
						echo $msg;
						$create_video_log['status'] = 8;
						$create_video_log['msg'] = $msg;
						// $this->db->insert("create_video_log", $create_video_log);
					}
					if(!empty($user_anchor_log_data)) {
						$this->db->where('id',$val['id']);
						$this->db->update('user_anchor_log', $user_anchor_log_data);
					}
					$this->db->insert("create_video_log", $create_video_log ? $create_video_log : 'video log is null');
					echo ' Update Anchor Log Info :'.$this->db->last_query().'<br/>';
				}
			}
		}
		/**
		* 函数功能介绍：返回对流进行处理的业务
		* 创建人: 	Zhang Shaowei
		* 创建时间: 2016-01-12 17:20
		* 最后修改人：
		* 最后修改时间：
		*/
		function return_status_by_push($val = array(),$is_push = 0) {
			$this->load->library('redis',array('model'=>'anchor_redis','channel'=>'live'),'anchor_redis');
			$is_anchor_log = 0;//是否生成记录
			$data = array();
			
			//根据is_push设置数据
			if($is_push == 0 && empty($val['disconnect_time'])) { //第一次掉线
				$data['is_push'] = 0;
				$data['disconnect_time'] = time();
				
				$result1=$this->anchor_redis->redis_class->delete_redis_live_list($val['uid']);
				
				write_to_db_logs('delete_live_list', "anchor_id:".$val['uid']);
			}else if ($is_push == 0 && empty($val['static']) && $val['disconnect_time'] <= (time() - 180)  ) { //掉线超过3分钟 and 不是常开
				$data['is_live']			= 0;
				$data['is_push']			= 0;
				$data['start_time']			= 0;
				$data['disconnect_time']	= 0;
				$data['continue_time'] 		= 0;//清除重链状态
				$data['end_time']			= 0;
				$this->anchor_redis->redis_class->end_live($val['uid']);
				
			}else if ($is_push == 0) {
				$data['is_push'] = 0;
				$result1=$this->anchor_redis->redis_class->delete_redis_live_list($val['uid']);
				
				write_to_db_logs('delete_live_list', "anchor_id:".$val['uid']);
			}else if ($is_push == 1){
				$data['is_live'] = 1;
				$data['is_push'] = 1;
				
				//查看主播信息是否已经缓存列表
				$anchor_details=$this->anchor_redis->redis_class->get_live_info($val['uid']);
				if($anchor_details){//已存在表示重连
					$anchor_details['uid']=$val['uid'];
					$result1=$this->anchor_redis->redis_class->save__redis_live_list($anchor_details);
					
					write_to_db_logs('save_live_list', "anchor_id:".$val['uid']);
				}else{
					// $cdn=isset($val['cdn'])?$val['cdn']:4;
					// $this->anchor_redis->redis_class->start_live($val['uid'],$cdn);
				}
				
				$data['disconnect_time'] = 0;
			}else {
				$data['disconnect_time'] = 0;
			}
			$data['continue_time'] = 0;
			//如果是常设置is_live is_push为常开
			if(!empty($val['static']) && $val['static']==1){
				$data['is_live'] = 1;
				$data['is_push'] = 1;
			}
			return $data;
		}

		function cc_start(){
			file_put_contents('uploads/logs/callback/lanxun_1.txt', json_encode($_GET));
			//$notifyData = file_get_contents('php://input','r');
			//$notifyData = json_decode($notifyData, true);
			//file_put_contents('uploads/logs/callback/lanxun_' . time() . '.txt', json_encode($notifyData));
		}

		function cc_end(){
			file_put_contents('uploads/logs/callback/lanxun_2.txt', json_encode($_GET));
			$notifyData = file_get_contents('php://input','r');
			$notifyData = json_decode($notifyData, true);
			file_put_contents('uploads/logs/callback/lanxun_' . time() . '.txt', json_encode($notifyData));
		}
		
		function chk_anchor_beat_end_live(){
			return false;
			$this->load->library('redis',array('model'=>'anchor_redis','channel'=>'anchor'),'anchor_redis');
			$cron_anchor_beat_status = $this->anchor_redis->redis_class->chk_cron_anchor_beat();
			if($cron_anchor_beat_status){
				exit('croning');
			}
			register_shutdown_function('shutdown_func'); 
			$this->anchor_redis->redis_class->begin_cron_anchor_beat();
			$this->anchor_redis->redis_class->anchor_beat_end_live();
			echo 'ok';exit;
		}
	}

	//程序结束后执行的函数
	function shutdown_func(){
		$CI =& get_instance();
		$CI->load->library('redis',array('model'=>'anchor_redis','channel'=>'anchor'),'anchor_redis');
		$CI->anchor_redis->redis_class->end_cron_anchor_beat();
		echo 'end';
	}

	function aliyun_video_callback_live(){
		write_to_db_logs('create_video', date('H:i:s')." ".$_SERVER['REQUEST_URI']."\r\n");
	}
